<?php

namespace app\api\controller;


use app\common\controller\Api;
use app\common\model\Banner;
use app\common\model\Category;
use app\common\model\Options;
use app\common\model\Project as ProjectModel;
use app\common\model\Question;
use app\common\model\UserAnswers;
use app\common\model\UserRecord;
use think\Db;
use think\Request;

/**
 * 测评题
 */
class Project extends Api
{
    protected $noNeedLogin = ['index'];
    protected $noNeedRight = ['*'];


    public function _initialize()
    {
        parent::_initialize();
        $this->goodsModel = new \app\admin\model\jeek\shop\SkuGoods;
    }


    /**
     * Account:所有的测评项目
     * User: Ixiangang
     * Date: 2025/1/21
     * Time: 17:39
     */
    public function list(Request $request)
    {
        $category_id = $request->param('category_id');
        $keyword = $request->param('keyword');
        $where = [];
        if ($category_id) {
            $where['category_id'] = $category_id;
        }
        if ($keyword) {
            $where['name'] = ['like', '%' . $keyword . '%'];
        }
        $where['status'] = 'normal';
        $order = ['survey' => 'desc'];
        $field = "id,name,type,image,survey";
        $list = ProjectModel::where($where)
            ->field($field)
            ->order($order)
            ->paginate()
            ->each(function ($item) use (&$extend, &$result) {
                # 查询咨询师分类
                $item->questionCount = Question::where('project_id', $item->id)->count();
                #查询用户测评该项目没
                $user_record = UserRecord::where(['project_id' => $item->id, 'user_id' => $this->auth->id])->find();
                $item->user_record = !empty($user_record) ? 1 : 0; //1= 测评过 0=未测评
            });
        $this->success('success', ['projects' => $list]);
    }


    /**
     * Account:首页测评题、咨询师
     * User: Ixiangang
     * Date: 2025/1/13
     * Time: 11:02
     */
    public function index(Request $request)
    {
        $category_id = $request->param('category_id');
        $keyword = $request->param('keyword');
        $where = [];
        if ($category_id) {
            $where['category_id'] = $category_id;
        }
        if ($keyword) {
            $where['name'] = ['like', '%' . $keyword . '%'];
        }
        $where['status'] = 'normal';
        $order = ['survey' => 'desc'];
        $field = "id,name,type,image,survey";
        $list = ProjectModel::where($where)->field($field)->limit(5)->order($order)->select();
        collection($list)->each(function ($v, $k) {
            # 查询项目题数
            $v['questionCount'] = Question::where('project_id', $v['id'])->count();
            #查询用户测评该项目没
            if ($this->auth->id){
                $user_record = UserRecord::where(['project_id' => $v['id'], 'user_id' => $this->auth->id])->find();
                $v['user_record'] = !empty($user_record) ? 1 : 0; //1= 测评过 0=未测评
            }else{
                $v['user_record'] = 0;
            }

        });
        # 查询咨询师
        $skuGoods = $this->goodsModel->getList(['category_id' => $category_id], '', 10);
        $this->success('success', ['projects' => $list, 'skugoods' => $skuGoods]);
    }


    /**
     * Account:查询所有题
     * User: Ixiangang
     * Date: 2025/1/13
     * Time: 13:40
     */
    public function question($project_id)
    {
        $where['q.status'] = 'normal';
        $where['q.project_id'] = $project_id;
        $order = ['q.weigh' => 'asc'];
        $field = "q.id,q.name,q.type,q.image,q.description,p.type as project_type,p.id as project_id";
        $list = Question::alias('q')
            ->join('fa_project p', 'p.id = q.project_id')
            ->where($where)
            ->field($field)
            ->order($order)
            ->select();
        collection($list)->each(function ($v, $k) use ($project_id) {
            # 查询项目题数
            $v['options'] = Options::where(['question_id' => $v['id'], 'status' => 'normal'])->order(['weigh' => 'asc'])->field('id,tag,title,image,trigger_type,trigger_value,score')->select();
            # 查询已做过题目
            $userAnswers = UserAnswers::where(['user_id' => $this->auth->id, 'question_id' => $v['id'], 'project_id' => $project_id])->select();
            $v['user_answers'] = empty($userAnswers) ? [] : $userAnswers;
        });
        $this->success('success', $list);
    }


    /**
     * Account:答题
     * User: Ixiangang
     * Date: 2025/1/13
     * Time: 16:29
     */
    public function answerQuestion($question_id, $answer_id, $project_id)
    {
        $user_id = $this->auth->id;
        throw_validate_error(!$answer_id, "请提交答案");
        $question = Question::where('id', $question_id)->field('id,type')->find();
        if (empty($question)) {
            $this->error('题库信息错误');
        }
        $answer = Question::isAnswerRight($question_id, $answer_id, $project_id);
        # 查询用户是否答题
        $theAnswer = UserAnswers::where(['user_id' => $user_id, 'question_id' => $question_id, 'project_id' => $project_id])->find();
        if (!empty($theAnswer)) {
            $theAnswer->answer = $answer['tag'];
            $theAnswer->inner = $answer['title'];
            $theAnswer->score = $answer['score'];
            $theAnswer->redirect_question_id = $answer['trigger_value'];
            $theAnswer->trigger_type = $answer['trigger_type'];
            $theAnswer->options_id = $answer_id;
            $theAnswer->save();
        } else {
            $answersArr = [
                'user_id' => $user_id,
                'project_id' => $project_id,
                'question_id' => $question_id,
                'project_type' => $answer['project_type'], //测评类型:1=单题,2=计分题,3=跳转题,4=选项多
                'answer' => $answer['tag'],
                'inner' => $answer['title'],
                'score' => $answer['score'],
                'redirect_question_id' => $answer['trigger_value'],
                'trigger_type' => $answer['trigger_type'],
                'options_id' => $answer_id,
            ];
            UserAnswers::create($answersArr);
        }
        $this->success("提交成功");
    }


    /**
     * Account:查询当前用户测评结果
     * User: Ixiangang
     * Date: 2025/1/14
     * Time: 10:46
     */
    public function getResult(Request $request)
    {
        $user_id = $this->auth->id;
        $project_id = $request->param('project_id');  //测评项目ID
        $project = ProjectModel::where('id', $project_id)->find();
        if (empty($project)) {
            $this->error('测评项目不存在');
        }
        # 测评类型
        $type = $project->type;
        # 测评结果
        $data = UserAnswers::setResult($project_id, $type, $user_id);
        $result_data = json_decode($data->result_json, true);
        # 查询用户信息
        $user = $this->auth->getUser();
        # 咨询师
        $skugoods = $this->goodsModel->getList(['category_id' => $project->category_id], '', 10);
        $row = [
            'user_record_id' => $data->id,
            # 用户数据
            'user' => [
                'nickname' => $user['nickname'],
                'avatar' => $user['avatar'],
            ],
            # 测评报告
            'result' => [
                'score' => $data->score,
                'answer' => $data->answer,
                'result_data' => $result_data['grading'],
            ],
            'skugoods' => $skugoods,

        ];
        $this->success('success', $row);
    }

    /**
     * Account:测评详情
     * User: Ixiangang
     * Date: 2025/1/15
     * Time: 17:20
     */
    public function getResultDetails(Request $request)
    {
        # 报告ID
        $user_record_id = $request->post('user_record_id');
        $userRecordInfo = UserRecord::where('id', $user_record_id)->find();
        if (empty($userRecordInfo)) {
            $this->error("测评报告不存在！");
        }
        $result_data = json_decode($userRecordInfo->result_json, true);
        $result = [
            'createtime' => $userRecordInfo->createtime,
            'score' => is_numeric($userRecordInfo->score) ? $userRecordInfo->score . "分" : $userRecordInfo->score,
            'answer' => $userRecordInfo->answer,
            'grading' => $result_data['grading'],
            'question' => $result_data['question']
        ];
        $this->success('success', $result);
    }


    /**
     * Account:测评记录 查询完成测评
     * User: Ixiangang
     * Date: 2025/1/15
     * Time: 17:33
     */
    public function getRecordLog()
    {
        $user_id = $this->auth->id;
        $field = "ur.id,ur.user_id,ur.project_id,ur.score,ur.answer,ur.createtime,p.name,p.image";
        $list = UserRecord::alias('ur')
            ->join('fa_project p', 'p.id = ur.project_id')
            ->field($field)
            ->where(['ur.user_id' => $user_id])
            ->select();
        $this->success('success', $list);
    }

    /**
     * Account:重新测评(删除之前测评结果)
     * User: Ixiangang
     * Date: 2025/1/16
     * Time: 09:44
     */
    public function againEvaluation($project_id)
    {
        $user_id = $this->auth->id;
        $info = ProjectModel::where('id', $project_id)->find();
        if (empty($info)) {
            $this->error("测评项目不存在");
        }
        # 删除之前测评结果
        $rs1 = UserRecord::where(['user_id' => $user_id, 'project_id' => $project_id])->delete();
        $rs2 = UserAnswers::where(['user_id' => $user_id, 'project_id' => $project_id])->delete();
        if ($rs1 && $rs2) {
            $this->success('重新测评');
        }
        $this->error("删除失败");
    }


    /**
     * Account:测评题（记录---未答完题）
     * User: Ixiangang
     * Date: 2025/2/11
     * Time: 19:12
     */
    public function getRecordList(Request $request)
    {
        $user_id = $this->auth->id;
        # 查询 已答过的测评题目
        $project_ids = UserAnswers::where(['user_id' => $user_id])->group('project_id')->column('project_id');
        $field = "id,name,image";
        $list = ProjectModel::field($field)
            ->where('id', 'in', $project_ids)
            ->select();
        array_map(function ($item) use ($user_id) {
            # 查询是否完成测评
            $userRecord = UserRecord::where(['project_id' => $item['id'], 'user_id' => $user_id])->find();
            if (!empty($userRecord)) {
                $item->evaluationIs = 1; //测评完成
                $result_data = json_decode($userRecord->result_json, true);
                $item->user_record = ['score' => $userRecord->score, 'grading' => $result_data['grading']];
                $item->createtime = $userRecord->createtime;
            } else {
                $item->evaluationIs = 0; //继续测评
                $item->createtime = UserAnswers::where(['project_id' => $item['id'], 'user_id' => $user_id])->value('createtime');
            }
        }, $list);
        $this->success('success', $list);
    }

}